package service

import (
	"chatgpt/models"
	"chatgpt/pkg/repository"
	"encoding/json"
	"strings"
)

type ChatService interface {
	GenerateResponse(models.ChatMessage) error
	FetchAllMessages(string) ([]models.ChatMessage, error)
	ClearChatHistory(string) error
}

type ChatEngine struct {
	model string
	repo  *repository.Repository
}

func NewChatEngine(repo *repository.Repository, model string) ChatService {
	return &ChatEngine{
		model: model,
		repo:  repo,
	}
}

func (engine *ChatEngine) FetchAllMessages(IdProfile string) ([]models.ChatMessage, error) {
	return engine.repo.Redis.GetChatHistory(IdProfile)

}

func (engine *ChatEngine) ClearChatHistory(id string) error {

	err := engine.repo.Redis.SetChatHistory(id, []models.ChatMessage{})
	if err != nil {
		return err
	}
	return nil
}

func (engine *ChatEngine) GenerateResponse(chatMessage models.ChatMessage) error {
	chatMessage.Message = strings.TrimSpace(chatMessage.Message)

	userMessage := models.ChatMessage{Role: "user", Message: chatMessage.Message, IdProfile: chatMessage.IdProfile}

	history, err := engine.repo.Redis.GetChatHistory(chatMessage.IdProfile)
	if err != nil {
		return err
	}

	history = append(history, userMessage)

	tempHistory := make([]models.ApiChatMessage, len(history))

	for i, msg := range history {
		tempHistory[i] = models.ApiChatMessage{
			Role:    msg.Role,
			Message: msg.Message,
		}
	}

	requestBody, err := json.Marshal(models.ChatRequest{
		Model:     engine.model,
		Messages:  tempHistory,
		MaxTokens: 2048,
	})
	if err != nil {
		return err
	}

	responseBody, err := engine.repo.ChatApi.SendRequest(requestBody)
	if err != nil {
		return err
	}

	var completion models.ChatCompletion
	err = json.Unmarshal(responseBody, &completion)
	if err != nil {
		return err
	}

	assistantMessage := models.ChatMessage{Role: "assistant", Message: completion.Choices[0].Message.Content, IdProfile: chatMessage.IdProfile} //бывает вылетает паника когда ключ дохлый, починить!

	history = append(history, assistantMessage)
	engine.repo.Redis.SetChatHistory(chatMessage.IdProfile, history)

	return nil
}
